package org.txazo.blog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.txazo.blog.commons.cache.IPVisitCache;
import org.txazo.blog.util.HttpUtil;

/**
 * IP攻击拦截器
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-10
 * 
 */
public class IPAttackDefendFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;

		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		IPVisitCache ipVisitCache = (IPVisitCache) context
				.getBean("ipVisitCache");

		String ip = HttpUtil.getRemoteIp(request);

		Object countObject = ipVisitCache.get(ip);
		if (countObject != null) {
			Integer count = (Integer) countObject;
			if (count > 100) {
				/** 频繁的IP攻击 */
				if (request.getRequestURI().equals("/common/ip.jsps")) {
					chain.doFilter(req, resp);
				} else {
					response.sendRedirect(HttpUtil
							.getFullRedirectURL("/common/ip.jsps"));
				}
			} else {
				if (request.getRequestURI().equals("/common/ip.jsps")) {
					response.sendRedirect(HttpUtil
							.getFullRedirectURL("/index.jsps"));
				} else {
					ipVisitCache.set(ip, count + 1);
					chain.doFilter(req, resp);
				}
			}
		} else {
			if (request.getRequestURI().equals("/common/ip.jsps")) {
				response.sendRedirect(HttpUtil
						.getFullRedirectURL("/index.jsps"));
			} else {
				ipVisitCache.set(ip, 1);
				chain.doFilter(req, resp);
			}
		}
	}

	@Override
	public void destroy() {
	}

}
